(function() {
	var $ = require(L('$')), _ = require(L('_'));

	var retailer = {
		hasFiltered : false,
		productVariantInfoList : null,
		filterDistance : 5000
	};

	retailer.showRetailerOptionsDialog = function(productVariantInfoList, callback) {
		retailer.hasFiltered = false;
		retailer.productVariantInfoList = productVariantInfoList;
		if ($.isEnableLocationService())
			$.gps().getCurrentPosition(callbackGetCurrentPosition);
		else
			callbackGetCurrentPosition(null);
	};

	function callbackGetCurrentPosition(locationData) {
		if (locationData != null)
			createMultiProductVariantItemAlertDialog(retailer.filterStoreByLocation(locationData, retailer.productVariantInfoList)).show();
		else
			$.ui('popup').enter_suburb(suburbPromptCallback).open();
	}

	function suburbPromptCallback(txtSuburb) {
		var storesFilteredBySuburb = new Array();
		txtSuburb = txtSuburb.toLowerCase();
		var splitedSuburb = txtSuburb.split(' ');
		var found = false;
		for (var i = 0, j = splitedSuburb.length; i < j; i++) {
			if (found)
				break;
			if (!$.isNull(splitedSuburb[i])) {
				var keyword = splitedSuburb[i];
				for (var k = 0, h = retailer.productVariantInfoList.length; k < h; k++) {
					var suburb = retailer.productVariantInfoList[k].RetailerStoreSuburb;
					var splitedRetailerSuburb = suburb.split(' ');
					if (!$.isNull(suburb) && splitedRetailerSuburb.indexOf(keyword) > -1) {
						storesFilteredBySuburb.push(retailer.productVariantInfoList[k]);
						retailer.productVariantInfoList.splice(k, 1);
						storesFilteredBySuburb = storesFilteredBySuburb.concat(retailer.productVariantInfoList);
						found = true;
						break;
					}
				}
			}
		}
		if (storesFilteredBySuburb.length == 0) {
			$.a('We cannot find any stores in this "' + txtSuburb + '" suburb.', 'Sorry', ['View all stores'], function(e) {
				buildStoreListOptionDialog(retailer.productVariantInfoList);
			});
		} else {
			var alertDialog = createMultiProductVariantItemAlertDialog(storesFilteredBySuburb);
			alertDialog.show();
		}
	};

	function buildStoreListOptionDialog(filteredRetailers) {
		var retailerNames = retailer.getRetailerNames(filteredRetailers);
		retailerNames.push('Cancel');
		var optionDialog = Ti.UI.createOptionDialog({
			title : 'Please select a store',
			options : retailerNames,
			destructive : -1,
			cancel : -1,
			buttonNames : ['Cancel'],
			borderWidth : 1,
			borderColor : "red"
		});
		optionDialog.cancel = optionDialog.options.length - 1;
		if (retailer.hasFiltered) {
			optionDialog.title = 'Select a store\n(sorted by nearest location within ' + retailer.filterDistance + ' m)';
			optionDialog.selectedIndex = 0;
		}
		optionDialog.addEventListener('click', function(e) {
			if (e.index >= 0 && e.index !== e.cancel) {
				retailer.selectedRetailer = filteredRetailers[e.index];
				if (retailer.selectedRetailer)
					$.openProductDetails(retailer.selectedRetailer.ProductVariantID, retailer.selectedRetailer.RetailerStoreID, false, true);
			}
		});
		_.delay(function() {
			optionDialog.show();
		}, 500);
	}

	function createMultiProductVariantItemAlertDialog(filteredRetailers) {
		var alertDialog = Ti.UI.createAlertDialog({
			title : 'Notification',
			message : 'We think you are at ' + filteredRetailers[0].FullName + '?',
			buttonNames : ['YES', 'NO'],
			cancel : 1,
			data : filteredRetailers
		});
		alertDialog.addEventListener('click', function(e) {
			if (e.index == 0)
				$.openProductDetails(e.source.data[0].ProductVariantID, e.source.data[0].RetailerStoreID, false, true);
			else if (e.cancel)
				buildStoreListOptionDialog(e.source.data);
		});
		return alertDialog;
	};

	retailer.showRetailerUserShoppingOptionDialog = function(callback) {
		$.webservice().getRetailersUserShopping(function(responseText) {
			if (!PublicFunctions.isNullOrEmpty(responseText)) {
				var retailers = retailer.filterRetailersByIDs(JSON.parse(responseText));
				var retailerNames = retailer.getRetailerNames(retailers);
				var optionDialog = Ti.UI.createOptionDialog({
					title : 'Select a store',
					options : retailerNames,
					cancel : -1,
					buttonNames : ['Cancel'],
				});
				optionDialog.addEventListener('click', function(e) {
					if (callback)
						callback(retailers[e.index]);
				})
				optionDialog.show();
			}
		});
	};
	retailer.getRetailerNames = function(retailers) {
		var retailerNames = [];
		for (var i = 0, j = retailers.length; i < j; i++) {
			retailerNames.push(retailers[i].FullName);
		}
		return retailerNames;
	};
	retailer.filterStoreByLocation = function(currentLocation, stores) {
		var result = [];
		for (var i = 0, j = stores.length; i < j; i++) {
			var store = stores[i];
			var distance = $.gps().calculateDistance(currentLocation.latitude, currentLocation.longitude, store.Latitude, store.Longitude, 'M');
			store.distanceFromThisLocation = distance;
			result.push(store);
			retailer.hasFiltered = true;
		}
		if (result.length === 0)
			return stores.sort(retailer.orderByDistance);
		else
			return result.sort(retailer.orderByDistance);
	};
	retailer.filterRetailersByIDs = function(arrayRetailerIDs) {
		var result = _.sortBy(arrayRetailerIDs, function(item) {
			return item;
		})
		return result;
	};
	retailer.orderByDistance = function(retailer1, retailer2) {
		return parseFloat(retailer1.distanceFromThisLocation) - parseFloat(retailer2.distanceFromThisLocation);
	};
	module.exports = retailer;
})();
